package yf.mall.service.impl;

import com.yf.response.RRException;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import yf.mall.dao.*;
import yf.mall.entity.ShopEntity;
import yf.mall.entity.ShopParamEntity;
import yf.mall.entity.SysUsersEntity;
import yf.mall.entity.UserEntity;
import yf.mall.enums.ShopStatusEnum;
import yf.mall.service.NoticeService;
import yf.mall.service.ShopService;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.vo.ShopTypeVo;

/**
 * 店铺Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Sun May 24 13:54:38 CST 2020
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<ShopEntity> implements ShopService {

    private ShopDao shopDao;


    @Autowired
    public void setDao(ShopDao shopDao) {
        this.shopDao = shopDao;
        super.setBaseDao(shopDao);
    }

    @Autowired
    private ShopParamDao shopParamDao;



    /**
     *
     *   @Override
     *     public List<UserVo> queryListVo(UserVo userVo) {
     *         return userDao.queryListVo(userVo);
     *     }
     *
     *     @Override
     *     public UserVo getVo(Long id) {
     *         return userDao.getVo(id);
     *     }



     **/


    /**内部方法**/
/*
    @Override
    public List<ShopVo> queryListVo(ShopVo shopVo){
        return shopDao.queryListVo(shopVo);
    }

    @Override
    public ShopVo getVo(Long id){
        return shopDao.getVo(id);
    }*/

    @Autowired
    private SysUsersDao sysUsersDao;
    @Autowired
    private NoticeService noticeService;

    /**
     * 用户开店 que
     * @param shopVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopEntity openShop(ShopTypeVo shopVo) {
            String str = shopVo.getSysUsersEntity().getPassword().replaceAll(" ", "");//去空格
            shopVo.getSysUsersEntity().setPassword(str);
        //  isUserCodeExistence(shop);
            ShopEntity shop = shopVo.getShop();
            //判断编号是否存在
            UserEntity userEntity = codeIsExist(shop);
            ShopEntity shopEntity = shopDao.findByUserId(userEntity.getId());
            //如果是审核或者通过状态则不允许在申请
            if (shopEntity != null){
                if(shopEntity.getStatus() == ShopStatusEnum.PASS.getIndex()||shopEntity.getStatus() == ShopStatusEnum.AUDIT.getIndex()){
                    throw new RRException("该用户已开通店铺");
                }
            }
            ShopEntity shopEntityByName = shopDao.findByName(shop.getName());
            if (shopEntityByName != null && !shopEntity.getStatus().equals(ShopStatusEnum.NOPASS.getIndex()) && shopEntityByName.getUserId() != userEntity.getId()){
//        if (shopEntityByName != null && !userEntity.getId().equals(shopEntityByName.getUserId())){
                throw new RRException("该店铺名已存在");
            }
            //保存用户名和密码
            SysUsersEntity sysUser = sysUsersDao.findByUserName(shopVo.getSysUsersEntity().getUsername());
            if (sysUser != null){
                if (!sysUsersDao.findBySysUserId(sysUser.getUserId()).equals(userEntity.getId())){
                    throw new RRException("该用户名已存在");
                }
            }
            //初始化系统用户信息
            shopVo.getSysUsersEntity().setPassword((new Sha256Hash(shopVo.getSysUsersEntity().getPassword())).toHex());
            shopVo.getSysUsersEntity().setStatus(0);
            shopVo.getSysUsersEntity().setCreateTime(new Date());
            shopVo.getSysUsersEntity().setCreateUserId(1L);

            shop.setUserId(userEntity.getId());
            shop.setStatus(ShopStatusEnum.AUDIT.getIndex());
            //如果查询的店铺不为空 则直接修改店铺
            if (shopEntity != null){
                shop.setId(shopEntity.getId());
                shopDao.update(shop);
                //修改系统用户和密码
                //根据用户名查找 如果存在并且属于该用户 则修改
                SysUsersEntity sysusersEntity = sysUsersDao.findByUserName(shopVo.getSysUsersEntity().getUsername());
                if (sysusersEntity != null){
                    Long userId = sysUsersDao.findBySysUserId(sysusersEntity.getUserId());
                    if (userId != null && userId.equals(userEntity.getId())){
                        shopVo.getSysUsersEntity().setUserId(sysusersEntity.getUserId());
                        sysUsersDao.update(shopVo.getSysUsersEntity());
                    }
                }else {
                    sysUsersDao.save(shopVo.getSysUsersEntity());
                    sysUsersDao.saveUserIdAndSysUserId(shopVo.getSysUsersEntity().getUserId(),shop.getUserId());
                    //添加店家权限
                    sysUsersDao.saveRole(shopVo.getSysUsersEntity().getUserId(),18L);
                }
            }else {
                shopDao.save(shop);
                shopParamDao.saveShopParam(shop.getId(),new BigDecimal(20));
                sysUsersDao.save(shopVo.getSysUsersEntity());
                sysUsersDao.saveUserIdAndSysUserId(shopVo.getSysUsersEntity().getUserId(),shop.getUserId());
                //添加店家权限
                sysUsersDao.saveRole(shopVo.getSysUsersEntity().getUserId(),18L);
            }
            this.noticeService.sendOpenShop(shop.getShopPhone(),shop.getName());
            return shop;
        }

    @Override
    public List<ShopEntity> findByType(Integer type) {
        return shopDao.findByType(type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteShop(String userCard, UserEntity userEntity) {
        shopDao.delShop(userEntity.getId(),userCard);
        //删除绑定的系统用户
        List<Long> sysUsers = sysUsersDao.findByUserId(userEntity.getId());
        if (sysUsers != null && sysUsers.size() > 0){
            for (Long sysUserId : sysUsers) {
                sysUsersDao.delete(sysUserId);
                //删除绑定的权限
                shopDao.delRoleBySysUserId(sysUserId);
            }
        }
        sysUsersDao.delByUserId(userEntity.getId());
    }
   @Autowired
   private MallGoodsDao mallGoodsDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delByShopId(Long[] ids) {
        //删除店铺 同时删除系统账号
        if (ids != null && ids.length > 0){
            for (Long shopId : ids) {
                ShopEntity shopEntity = shopDao.get(shopId);
                //获取系统账号
                List<Long> sysUserIds = sysUsersDao.findByUserId(shopEntity.getUserId());
                if (sysUserIds != null && sysUserIds.size() > 0){
                    //转成数组 批量删除系统账号
                    Long[] sysIds = sysUserIds.toArray(new Long[sysUserIds.size()]);
                    sysUsersDao.deleteBatch(sysIds);
                }
                //删除中间表中的数据
                sysUsersDao.delByUserId(shopEntity.getUserId());
                //删除对应的产品
                mallGoodsDao.delByUserId(shopEntity.getUserId());
            }
        }
        shopDao.deleteBatch(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopEntity updateShop(ShopTypeVo shopTypeVo) {
        // isUserCodeExistence(shop);
        ShopEntity shop = shopTypeVo.getShop();
        //判断编号是否存在
        UserEntity userEntity = codeIsExist(shop);
        shop.setUserId(userEntity.getId());
        shopDao.update(shop);
        //当店铺审核通过后 修改店铺拥有者后台登陆账号的的状态
        if (shop.getStatus() == ShopStatusEnum.PASS.getIndex()){
            List<Long> sysUsers = sysUsersDao.findByUserId(shop.getUserId());
            if (sysUsers != null && sysUsers.size() > 0){
                for (Long sysUserId : sysUsers) {
                    sysUsersDao.updateStatus(sysUserId);
                }
            }
            //审核通过设置发布素材奖励优惠券
            ShopParamEntity shopParamEntity = shopParamDao.findByShopId(shop.getId());
            if (shopParamEntity == null){
                shopParamDao.saveShopParam(shop.getId(),new BigDecimal(20));
            }
            noticeService.sendShopPass(shop.getShopPhone(),shop.getShopName(),shop.getName());
        }
        if (shop.getStatus().equals(ShopStatusEnum.NOPASS.getIndex())||shop.getStatus().equals(ShopStatusEnum.AUDIT.getIndex())){
            noticeService.sendShopNoPass(shop.getShopPhone(),shop.getShopName(),shop.getRemark());
        }
        return shop;
    }

    @Autowired
        private UserDao userDao;
    /**
     *  que
     *  判断用户编号和管理员是否存在
     * @param shop
     */
    private UserEntity codeIsExist(ShopEntity shop) {
        if (shop.getMcode() != null) {
            UserEntity mUser = userDao.findByCode(shop.getMcode());
            if (mUser == null) {
                throw new RRException("服务人编号不存在");
            }
            shop.setMid(mUser.getId());
        }
        UserEntity userEntity = userDao.findByCode(shop.getUserCode());
        if (userEntity == null) {
            throw new RRException("用户编号不存在");
        }
        if (shop.getUserCode().equals(shop.getMcode())){
            throw new RRException("服务人不能是自己");
        }
        return userEntity;
    }

    /**外部方法实现**/
    @Override
    public ShopEntity findByUserId(Long userId) {
        return shopDao.findByUserId(userId);
    }

    @Override
    public ShopEntity findByName(String name) {
        return shopDao.findByName(name);
    }

    @Override
    public void delShop(Long uid, String card) {
        shopDao.delShop(uid,card);
    }

    @Override
    public void delRoleBySysUserId(Long sysUserId) {
        shopDao.delRoleBySysUserId(sysUserId);
    }

    @Override
    public List<ShopEntity> findAll(){
        return shopDao.findAll();
    };
}
